package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.album.client.TrackInfoFeignClient;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.UserPaidTrack;
import com.atguigu.tingshu.user.mapper.UserPaidTrackMapper;
import com.atguigu.tingshu.user.strategy.ItemTypeStrategy;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;
import java.util.stream.Collectors;


@Service("1002")
@Slf4j
public class TrackStrategy implements ItemTypeStrategy {

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;
    @Resource
    private TrackInfoFeignClient trackInfoFeignClient;


    @Override
    public int savePaidRecord(UserPaidRecordVo userPaidRecordVo) {

        int result = 0;
        if (SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(userPaidRecordVo.getItemType())){
            List<Long> itemIdList = userPaidRecordVo.getItemIdList();

            Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(itemIdList.get(0));

            Assert.notNull(trackInfoResult,"查询声音失败");
            TrackInfo trackInfo = trackInfoResult.getData();
            Assert.notNull(trackInfo,"查询声音失败");

            List<Long> userPaidTrackList = userPaidTrackMapper.selectList(new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getUserId, userPaidRecordVo.getUserId()).in(UserPaidTrack::getTrackId, itemIdList)).stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
            for (Long trackId : itemIdList) {
                if (userPaidTrackList.contains(trackId)){
                    log.warn("退款:"+trackId);
                }else {
                    UserPaidTrack userPaidTrack = new UserPaidTrack();
                    userPaidTrack.setUserId(userPaidRecordVo.getUserId());
                    userPaidTrack.setTrackId(trackId);
                    userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
                    userPaidTrack.setAlbumId(trackInfo.getAlbumId());
                    result += userPaidTrackMapper.insert(userPaidTrack);
                }
            }
        }


        return result;
    }
}
